import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:ecy_app_flutter/routes/blind_box/blind_box_list.dart';
import 'package:ecy_app_flutter/routes/blind_box/category_image_selector.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/EcyExchangeMarketPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxChoose extends StatefulWidget {
  const BlindBoxChoose({super.key,required this.commodityPageList});
  final List<BlindBoxPageMore> commodityPageList;
  @override
  State<BlindBoxChoose> createState() => _BlindBoxChooseState();
}

class _BlindBoxChooseState extends State<BlindBoxChoose> {
  _BlindBoxChooseState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);
  late final PageController _pageController;  // 修改为late

  int _currentPage = 1;
  bool _hasMore = false;
  List<BlindBoxPageMore> _packetinfoVoList = [];
  int _previousPage = 0;  // 添加记录上一页的变量
  bool _isAnimating = false;  // 添加动画状态控制
  bool _isForward = true;     // 添加方向控制

  final List<int> indexList = List.filled(19, 0);
  int _currentBoxPage = 0;
  int _lastPage = 0;
  int? _pendingPage;

  bool showMultiDialog = false;
  List<bool> isSelected = List.filled(12, false); // 假设每页12个格子
  double pricePerItem = 15.0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      viewportFraction: 1.0,  // 设置为1.0，只显示当前页面
      initialPage: _currentBoxPage,
    );
    _refreshData("");
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      var response = await EcyRequestbasemanager().get("/app/api/app/commodityBlindBox/currBoxList/${widget.commodityPageList[0].commodityId}", {});
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          var packetinfoVoList = ((response["data"] ?? []) as List<dynamic>)
              .map((e) => BlindBoxPageMore.fromJson(e as Map<String, dynamic>))
              .toList();
          setState(() {
            _packetinfoVoList = packetinfoVoList;
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0XFFF5F5F5),
      appBar: AppBar(
        title: Text('${widget.commodityPageList[0].commodityName}', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w700, color: Color(0xFF000000)),),
        centerTitle: true,
        backgroundColor: const Color(0XFFF5F5F5),
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        actions: [
          GestureDetector(
              onTap: () {},
              child: Padding(
                padding: EdgeInsets.only(right: 12.w),
                child: Image.asset(
                  'assets/images/kf.png',
                  width: 24.w,
                  height: 24.h,
                ),
              )),
          GestureDetector(
              onTap: () {},
              child: Padding(
                  padding: EdgeInsets.only(right: 16.w),
                  child: Image.asset(
                    'assets/images/share.png',
                    width: 24.w,
                    height: 24.h,
                  )))
        ],
      ),
      body: _packetinfoVoList.isEmpty
          ? Center(child: CircularProgressIndicator())
          : (!showMultiDialog
              ? Column(
                  children: [
                    CategoryImageSelector(
                      commodityList: widget.commodityPageList
                              .expand((e) => e.commoditySkuVoList ?? <BlindBoxDetailMore>[])
                              .toList(),
                    ),
                    Padding(padding: EdgeInsets.only(top: 80.h)),
                    Container(
                      width: MediaQuery.of(context).size.width - 2 * 16.w,
                      height: 163.h,
                      color: Colors.transparent,
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child: PageView.builder(
                              controller: _pageController,
                              itemCount: _packetinfoVoList.length,
                              physics: ClampingScrollPhysics(),
                              onPageChanged: (index) {
                                if (!showMultiDialog) {  // 只在非弹窗状态下更新页码
                                  setState(() {
                                    _currentBoxPage = index;
                                  });
                                }
                              },
                              itemBuilder: (context, itemIndex) {
                                return Center(
                                  child: ClipRRect(
                                    borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                                    child: _buildSinglePageGrid(_packetinfoVoList[itemIndex]),
                                  ),
                                );
                              },
                            ),
                          ),
                          if (_packetinfoVoList.length > 1)
                            Positioned(
                              left: 0,
                              top: 0,
                              bottom: 0,
                              child: GestureDetector(
                                onTap: () {
                                  if (_currentBoxPage > 0) {
                                    _pageController.previousPage(
                                      duration: Duration(milliseconds: 300),
                                      curve: Curves.easeInOut,
                                    );
                                  }
                                },
                                child: Container(
                                  width: 40.w,
                                  height: 163.h,
                                  color: Colors.transparent,
                                  child: Center(
                                    child: Icon(
                                      Icons.chevron_left,
                                      color: _currentBoxPage > 0 ? Color(0xFFEA4B9B) : Colors.grey,
                                      size: 30,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          if (_packetinfoVoList.length > 1)
                            Positioned(
                              right: 0,
                              top: 0,
                              bottom: 0,
                              child: GestureDetector(
                                onTap: () {
                                  if (_currentBoxPage < _packetinfoVoList.length - 1) {
                                    _pageController.nextPage(
                                      duration: Duration(milliseconds: 300),
                                      curve: Curves.easeInOut,
                                    );
                                  }
                                },
                                child: Container(
                                  width: 40.w,
                                  height: 163.h,
                                  color: Colors.transparent,
                                  child: Center(
                                    child: Icon(
                                      Icons.chevron_right,
                                      color: _currentBoxPage < _packetinfoVoList.length - 1 ? Color(0xFFEA4B9B) : Colors.grey,
                                      size: 30,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10.h),
                    Text(
                      'No.${_packetinfoVoList[_currentBoxPage].boxCode}',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Color(0xFF8C8C8C),
                      ),
                    ),
                    Padding(padding: EdgeInsets.only(bottom: 80.h)),
                    _buildButton(),
                  ],
                ) : Container()),
      bottomNavigationBar: showMultiDialog && _packetinfoVoList.isNotEmpty
        ? _buildMultiSelectSettlementBar(_packetinfoVoList[_currentBoxPage])
        : (!showMultiDialog ? GestureDetector(
        onTap: () {
          showModalBottomSheet(
            context: context,
            isScrollControlled: true,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            builder: (context) => Container(
              height: MediaQuery.of(context).size.height * 0.8,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Center(child: EcyExchangeMarketPage()),
            ),
          );
        },
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          height: 82.h,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const Icon(CupertinoIcons.chevron_compact_up),
              SizedBox(height: 10.h),
              const Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text('互换集市'),
                ],
              ),
            ],
          ),
        ),
      ) : null),
    );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 70.w, height: 70.h, fit: BoxFit.cover);

  Widget _buildButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        MultiSelectButton(
          onPressed: () async {
            _lastPage = _currentBoxPage;
            setState(() {
              showMultiDialog = true;
            });
            await showGeneralDialog(
              context: context,
              barrierDismissible: true,
              barrierLabel: '',
              transitionDuration: Duration(milliseconds: 0),
              pageBuilder: (context, anim1, anim2) {
                List<bool> localSelected = List.from(isSelected);
                BlindBoxPageMore page = _packetinfoVoList[_currentBoxPage];
                int itemsPerRow = 4;
                int totalItems = 12;
                int rowCount = (totalItems / itemsPerRow).ceil();
                return Stack(
                  children: [
                    GestureDetector(
                      onTap: () {
                        Navigator.of(context).pop();
                        setState(() {
                          showMultiDialog = false;
                        });
                        // 使用addPostFrameCallback确保在下一帧执行跳转
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          _pageController.jumpToPage(_lastPage);
                          setState(() {
                            _currentBoxPage = _lastPage;
                          });
                        });
                      },
                      child: Container(
                        color: Colors.black.withOpacity(0.2),
                      ),
                    ),
                    Align(
                      alignment: Alignment.bottomCenter,
                      child: Material(
                        color: Colors.transparent,
                        child: Container(
                          height: 500.h,
                          child: StatefulBuilder(
                            builder: (context, setStateDialog) {
                              int selectedCount = localSelected.where((e) => e).length;
                              double total = selectedCount * pricePerItem;
                              return Column(
                                children: [
                                  Expanded(
                                    child: Container(
                                      color: Colors.transparent,
                                      child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          SizedBox(height: 12),
                                          Expanded(
                                            child: SingleChildScrollView(
                                              child: Column(
                                                children: List.generate(rowCount, (row) {
                                                  int start = row * itemsPerRow;
                                                  int end = (start + itemsPerRow > totalItems) ? totalItems : start + itemsPerRow;
                                                  return Row(
                                                    mainAxisAlignment: MainAxisAlignment.center,
                                                    children: List.generate(end - start, (i) {
                                                      int index = start + i;
                                                      bool isBought = page.packetInfoVoList?.any((box) => box.boxLocation == index) ?? false;
                                                      bool selected = localSelected[index];
                                                      return GestureDetector(
                                                        onTap: isBought
                                                            ? null
                                                            : () {
                                                                setStateDialog(() {
                                                                  localSelected[index] = !localSelected[index];
                                                                });
                                                              },
                                                        child: Container(
                                                          margin: EdgeInsets.all(2),
                                                          width: 48.w,
                                                          height: 48.w,
                                                          decoration: BoxDecoration(
                                                            color: isBought
                                                                ? Colors.grey[200]
                                                                : (selected ? Colors.pinkAccent.withOpacity(0.2) : Colors.white),
                                                            border: Border.all(
                                                              color: selected ? Colors.pink : Colors.grey[300]!,
                                                              width: selected ? 2 : 1,
                                                            ),
                                                          ),
                                                          child: Stack(
                                                            children: [
                                                              Center(
                                                                child: isBought
                                                                    ? Icon(Icons.block, color: Colors.grey, size: 20)
                                                                    : Image.network(
                                                                        "${widget.commodityPageList[0].mainImageUrl}",
                                                                        fit: BoxFit.cover,
                                                                        width: 48.w,
                                                                        height: 48.w,
                                                                      ),
                                                              ),
                                                              if (selected)
                                                                Positioned(
                                                                  right: 2,
                                                                  top: 2,
                                                                  child: Icon(Icons.check_circle, color: Colors.pink, size: 16),
                                                                ),
                                                            ],
                                                          ),
                                                        ),
                                                      );
                                                    }),
                                                  );
                                                }),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  TextButton(
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {
                                        showMultiDialog = false;
                                      });
                                      // 使用addPostFrameCallback确保在下一帧执行跳转
                                      WidgetsBinding.instance.addPostFrameCallback((_) {
                                        _pageController.jumpToPage(_lastPage);
                                        setState(() {
                                          _currentBoxPage = _lastPage;
                                        });
                                      });
                                    },
                                    child: Text('取消', style: TextStyle(color: Colors.grey)),
                                  ),
                                  Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                                    child: Row(
                                      children: [
                                        Checkbox(
                                          value: localSelected.asMap().entries.where((e) => !(page.packetInfoVoList?.any((box) => box.boxLocation == e.key) ?? false)).every((e) => e.value),
                                          onChanged: (val) {
                                            setStateDialog(() {
                                              for (int i = 0; i < localSelected.length; i++) {
                                                if (!(page.packetInfoVoList?.any((box) => box.boxLocation == i) ?? false)) {
                                                  localSelected[i] = val ?? false;
                                                }
                                              }
                                            });
                                          },
                                        ),
                                        Text('全选'),
                                        Spacer(),
                                        Text('合计: ￥${total.toStringAsFixed(2)}'),
                                        SizedBox(width: 12),
                                        ElevatedButton(
                                          style: ElevatedButton.styleFrom(
                                            backgroundColor: Colors.pinkAccent,
                                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                                          ),
                                          onPressed: selectedCount == 0
                                              ? null
                                              : () {
                                                  Navigator.of(context).pop();
                                                  setState(() {
                                                    isSelected = List.from(localSelected);
                                                    showMultiDialog = false;
                                                  });
                                                  // 使用addPostFrameCallback确保在下一帧执行跳转
                                                  WidgetsBinding.instance.addPostFrameCallback((_) {
                                                    _pageController.jumpToPage(_lastPage);
                                                    setState(() {
                                                      _currentBoxPage = _lastPage;
                                                    });
                                                  });
                                                },
                                          child: Text('去结算($selectedCount)'),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                  ],
                );
              },
            );
          },
        ),
        SingleSelectButton(
          onPressed: () {
            EcyRouter.push(context, EcyRouter.blindBoxOneChoose, {"commodityPageList": [widget.commodityPageList[0]]});
          },
        ),
      ],
    );
  }

  Widget _buildSinglePageGrid(BlindBoxPageMore page, {Key? key}) {  // 添加key参数
    int itemsPerRow = 4;
    int totalItems = 12;
    int rowCount = (totalItems / itemsPerRow).ceil();
    
    return Container(
      key: key,  // 使用传入的key
      padding: EdgeInsets.all(2),
      width: 210.w,
      color: Colors.white, 
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: List.generate(rowCount, (row) {
          int start = row * itemsPerRow;
          int end = (start + itemsPerRow > totalItems) ? totalItems : start + itemsPerRow;
          return Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(end - start, (i) {
              int index = start + i;
              bool isBought = page.packetInfoVoList?.any((box) => box.boxLocation == index) ?? false;
              
              return Container(
                margin: EdgeInsets.all(1),
                width: 48.w,  // 恢复到原来的尺寸
                height: 48.w,
                decoration: BoxDecoration(
                  color: isBought ? Colors.grey[200] : Colors.white,
                  border: Border.all(
                    color: isBought ? Colors.grey[300]! : Colors.grey[300]!,
                    width: 1,
                  ),
                ),
                child: Stack(
                  children: [
                    Center(
                      child: isBought
                          ? Icon(Icons.block, color: Colors.grey, size: 20)  // 恢复到原来的图标大小
                          : Image.network(
                              "${widget.commodityPageList[0].mainImageUrl}",
                              fit: BoxFit.cover,
                              width: 48.w,
                              height: 48.w,
                            ),
                    ),
                  ],
                ),
              );
            }),
          );
        }),
      ),
    );
  }

  Widget _buildMultiSelectSettlementBar(BlindBoxPageMore page) {
    int selectedCount = isSelected.where((e) => e).length;
    double total = selectedCount * pricePerItem;
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Row(
        children: [
          Checkbox(
            value: isSelected.asMap().entries.where((e) => !(page.packetInfoVoList?.any((box) => box.boxLocation == e.key) ?? false)).every((e) => e.value),
            onChanged: (val) {
              setState(() {
                for (int i = 0; i < isSelected.length; i++) {
                  if (!(page.packetInfoVoList?.any((box) => box.boxLocation == i) ?? false)) {
                    isSelected[i] = val ?? false;
                  }
                }
              });
            },
          ),
          Text('全选'),
          Spacer(),
          Text('合计: ￥${total.toStringAsFixed(2)}'),
          SizedBox(width: 12),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.pinkAccent,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            ),
            onPressed: selectedCount == 0
                ? null
                : () {
                    // 这里可以添加结算逻辑
                  },
            child: Text('去结算($selectedCount)'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    _pageController.dispose();
    super.dispose();
  }
}

// 新增：选多个按钮组件
class MultiSelectButton extends StatelessWidget {
  final VoidCallback onPressed;
  const MultiSelectButton({required this.onPressed, super.key});
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 140.w,
      height: 40.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: [Color(0xFFFFFFFF), Color(0xFFFFFFFF)]),
        borderRadius: BorderRadius.circular(24),
      ),
      child: TextButton(
        onPressed: onPressed,
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        ),
        child: Text('选多个', style: TextStyle(
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w700,
          fontSize: 16.sp,
          color: const Color(0xFFEA4B9B),
        )),
      ),
    );
  }
}

// 新增：选一个按钮组件
class SingleSelectButton extends StatelessWidget {
  final VoidCallback onPressed;
  const SingleSelectButton({required this.onPressed, super.key});
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 140.w,
      height: 40.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: [Color(0xFFFF7BBE), Color(0xFFFF3E9F)]),
        borderRadius: BorderRadius.circular(24),
      ),
      child: TextButton(
        onPressed: onPressed,
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        ),
        child: Text('选一个', style: TextStyle(
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w700,
          fontSize: 16.sp,
          color: const Color(0xFFFFFFFF),
        )),
      ),
    );
  }
}
